﻿#define _CRT_SECURE_NO_WARNINGS 1
#include"Queue.h"

void QueueInit(Queue* pq)
{
	pq->phead = NULL;
	pq->ptail = NULL;
	pq->size = 0;
}
// ⼊队列，队尾
void QueuePush(Queue* pq, QDataType x)
{
	assert(pq);
	QNode* tmp = (QNode*)malloc(sizeof(QNode));
	if (tmp == NULL)
	{
		perror("malloc!");
		exit(-1);
	}
	tmp->data = x;
	tmp->next = NULL;
	if (pq->phead == NULL)
	{
		pq->phead = pq->ptail = tmp;
	}
	else
	{
		pq->ptail->next = tmp;
		pq->ptail = tmp;
	}
	pq->size++;
}

//队列判空
bool QueueEmpty(Queue* pq)
{
	assert(pq);
	return pq->phead == NULL && pq->ptail == NULL;
	//return pq->phead == pq->ptail == NULL;//err
}


// 出队列，队头
void QueuePop(Queue* pq)
{
	assert(pq);
	assert(!QueueEmpty(pq));

	//只有一个结点的情况，避免ptail变成野指针
	if (pq->ptail == pq->phead)
	{
		free(pq->phead);
		pq->phead = pq->ptail = NULL;
	}
	else
	{
		//删除队头元素、
		QNode* next = pq->phead->next;
		free(pq->phead);
		pq->phead = next;
	}
	--pq->size;
}
//void QueuePop(Queue* pq)
//{
//	assert(pq);
//	QNode* del = pq->phead;
//	pq->phead = pq->phead->next;
//	free(del);
//	del = NULL;
//	pq->size--;
//}

//取队头数据
QDataType QueueFront(Queue* pq)
{
	assert(pq);
	return pq->phead->data;
}
//取队尾数据
QDataType QueueBack(Queue* pq)
{
	assert(pq);
	return pq->ptail->data;
}
//队列有效元素个数
int QueueSize(Queue* pq)
{
	assert(pq);
	return pq->size;
}

//销毁队列
void QueueDestroy(Queue* pq)
{
	QNode* del = pq->phead;
	while(del)
	{
		pq->phead = pq->phead->next;
		free(del);
		del = pq->phead;
	}
	pq->phead = NULL;
	pq->ptail = NULL;
	pq->size = 0;
}